package com.lgb.Service;

import com.lgb.DAO.AnnouncementRepository;
import com.lgb.Exceptions.NotFoundException;
import com.lgb.pojo.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AnnouncementServiceImpl implements  AnnouncementService{

    @Autowired
    private AnnouncementRepository announcementRepository;

    @Override
    public Announcement getOnlyone() {
        //获取全部的数据
        List<Announcement> announcementList = announcementRepository.findAll();
        //如果没有
        if(announcementList.size() == 0){
            throw new NotFoundException("当前没有公告内容");
        }else {
            return announcementList.get(0);
        }
    }

    @Override
    public Announcement saveAnnouncement(Announcement announcement) {
        //获取全部的数据
        List<Announcement> announcementList = announcementRepository.findAll();
        //如果没有
        if(announcementList.size() == 0){
            announcement.setCreateTime(new Date());
            return announcementRepository.save(announcement);
        }else {
            //获取唯一一个数据
            Announcement onlyone = announcementList.get(0);
            //对应id
            Long onlyid = onlyone.getId();
            //修改
            announcement.setId(onlyid);
            announcement.setCreateTime(new Date());
            return announcementRepository.save(announcement);
        }
    }
}
